package com.lcy.reggie.service.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcy.reggie.common.CustomException;
import com.lcy.reggie.common.Result;
import com.lcy.reggie.entity.*;
import com.lcy.reggie.service.*;
import com.lcy.reggie.mapper.OrdersMapper;
import com.lcy.reggie.utils.BaseContext;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author ChunBaBa_
 * @description 针对表【orders(订单表)】的数据库操作Service实现
 * @createDate 2023-01-17 16:11:41
 */
@Transactional
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 提交订单
     *
     * @param orders
     * @return
     */
    @Override
    public Result<String> submit(Orders orders) {
        //1.获取用户id
        Long userId = BaseContext.getCurrentId();
        //2.查询用户的购物车数据
        List<ShoppingCart> shoppingCarts = shoppingCartService.query().eq("user_id", userId).list();
        if (CollectionUtils.isEmpty(shoppingCarts)) {
            throw new CustomException("购物车为空，不能下单！");
        }

        //3.查询用户信息
        User user = userService.getById(userId);

        //4.查询地址信息
        Long addressBookId = orders.getAddressBookId();
        AddressBook address = addressBookService.getById(addressBookId);
        if (address == null) {
            throw new CustomException("收货地址为空，不能下单！");
        }

        long orderId = IdWorker.getId(); //订单号

        //原子操作，保证多线程情况下，计算也不会出错
        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //向订单表插入数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get())); //总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(address.getConsignee());
        orders.setPhone(address.getPhone());
        orders.setAddress((address.getProvinceName() == null ? "" : address.getProvinceName())
                + (address.getCityName() == null ? "" : address.getCityName())
                + (address.getDistrictName() == null ? "" : address.getDistrictName())
                + (address.getDetail() == null ? "" : address.getDetail()));

        //像订单插入数据
        this.save(orders);

        //像订单明细表插入数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCartService.removeBatchByIds(shoppingCarts);

        return Result.success("下单成功！");
    }

    /**
     * 查看订单
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result<Page> pageOrder(Integer page, Integer pageSize) {
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        Long userId = BaseContext.getCurrentId();
        Page<Orders> ordersPage = this.query().eq("user_id",userId).orderByDesc("checkout_time").page(pageInfo);
        return Result.success(ordersPage);
    }
}




